import axios from 'axios'
import Vue from 'vue'
import  { ToastPlugin } from 'vux'
import qs from 'qs'

export const ERR_LOGIN = -1;      // session失效
export const APP_TITLE = '乐趣投'
const instance = axios.create();

instance.defaults.withCredentials = true; 
instance.defaults.timeout = 30000;
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';

// 添加一个请求拦截器
instance.interceptors.request.use(config => {
  //store.commit('updateLoadingStatus', {isLoading: true})
  if(config.method!='get'){
        config.data=qs.stringify(config.data);
    }
  return config
}, error => {
  //store.commit('updateLoadingStatus', {isLoading: false})
  return Promise.reject(error)
})

// 添加一个响应拦截器
instance.interceptors.response.use(response => {
  //store.commit('updateLoadingStatus', {isLoading: false})
  // 在这里对返回的数据进行处理
  let status = response.status
  let resData = response.data
  if (status != 200) {
    return Promise.reject(response)
  }
  if(resData.errno == ERR_LOGIN) {
    Vue.$vux.toast.text('登录超时，请重新登录', 'top');
    if(Vue.$route){
      setTimeout(()=>{
        Vue.$route.push({path:'/login',query:{redirect:'/index'}});
      },1000)
    }
  }
  return Promise.resolve(resData)
}, error => {
  // response error
  //store.commit('updateLoadingStatus', {isLoading: false})
  Vue.$vux.toast.show({
    title: APP_TITLE,
    type: 'warn',
    text: '系统异常'
  })
  return Promise.reject(error)
})

export default {
  fetchGet (url, params = {}) {
    if (!navigator.onLine) {
      Vue.$vux.toast.show({
        title: APP_TITLE,
        type: 'warn',
        text: '网络异常'
      })
      return;
    }
    //let data = qs.stringify(params);
    return instance.get(url, params).then(res => {
        return res;
      }).catch(error => {
        console.log(error)
      })
  },
  fetchPost (url, params) {
    if (!navigator.onLine) {
      Vue.$vux.toast.show({
        title: APP_TITLE,
        type: 'warn',
        text: '网络异常'
      })
      return;
    }
    return instance.post(url, params).then(res => {
        return res;
      }).catch(error => {
        console.log(error)
      })

  }
}
